package com.nuanshui.framework.security;

import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

public class MD5Util {

	private static String byteArrayToHexString(byte b[]) {
		StringBuilder resultSb = new StringBuilder();
		for (int i = 0; i < b.length; i++)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String md5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("md5");
			if (charsetname == null || "".equals(charsetname))
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes()));
			else
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes(charsetname)));
		} catch (Exception exception) {
		}
		return resultString;
	}

	private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	
	// 来自stackoverflow的MD5计算方法，调用了MessageDigest库函数，并把byte数组结果转换成16进制
	public static String md5(String md5) {
		try {
			MessageDigest md = MessageDigest
					.getInstance("md5");
			byte[] array = md.digest(md5.getBytes());
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
						.substring(1, 3));
			}
			return sb.toString().toUpperCase();
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
	}

	public static String getMd5ByInputStream(InputStream in) {
		try{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte buffer[] = new byte[1024];
			int len = 0;
			while((len = in.read(buffer)) > 0){
				md5.update(buffer, 0, len);
			}
			BigInteger bigInt = new BigInteger(1, md5.digest());
			return bigInt.toString(16);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "";
	}

}
